/**
 * System 操作相关
 */
var System = (function () {
    /**
     * 查询版本号(包含当前版本、备份版本)
     * @return {Object} ack, object which is parsed by LMT.parser()
     */
    function getSWpackageVersion() {
        var cmd = "list package;", //
            data = LMT.cmdAsyn(cmd);
        return LMT.parser(data);
    }

    /**
     * 版本激活
     * @param {String} ver ,version to be active
     */
    function activePackage(ver) {
        var cmd = "active package : version = \"" + ver + "\"";

        Modal.progress();
        LMT.cmdSyn(cmd, function (data) {
            var ack = LMT.parser(data);

            if (ack.result === "000") {
                Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.VersionActiveSuccessInfo, "ok");
                Progress.reBooting();
            } else {
                Modal.delProgress();
                Modal.open(top.T.AlertInfo.OperationFail, top.T.AlertInfo.VersionActiveFailureInfo, "error");
            }
        });
    }

    /**
     * 数据库导出
     *  @return {Object} result ack object, which is parsed by LMT.parser()
     */
    function exportDatabase() {
        var cmd = "", data = "";

        if (USER.hasModule(Branch.Modules.VxWorks)) {
            cmd = "export database: path = \"/ram0/OAM/software/param.xml\";";
        } else {
            cmd = "export database: path = \"/OAM/software/param.xml\";"
        }

        data = LMT.cmdAsyn(cmd);
        return LMT.parser(data);
    }

    /**
     * 解压zip包命令
     *  @return {Object} result ack object, which is parsed by LMT.parser()
     */
    function zipExportPackage() {
        var data;
        if (USER.hasModule(Branch.Modules.VxWorks)) {
            data = LMT.cmdAsyn("web zipPackage:/ram0/OAM/software/param.xml /ram0/OAM/software/web/web_page/param.zip;");
        } else {
            data = LMT.cmdAsyn("web zipPackage:/OAM/software/param.xml /OAM/software/web/web_page/param.zip;");
        }

        return parent.LMT.parser(data);
    }

    /**
     * 数据库导入
     * @param {String} path, new database file path.
     */
    function importDatabase(path) {
        Modal.progress();
        var cmd = "import database: path = \"" + path + "\"";
        Modal.progress(top.T.AlertInfo.Importing);

        LMT.cmdSyn(cmd, function (data) {
            Modal.delProgress();

            var ack = LMT.parser(data), url = "business/config/BackupAndImportConfig.asp", ifNd = null;
            if (ack.result === "000") {
                Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.ImportSuccess, "ok");
                /* reBooting */
            } else {
                parent.Modal.open(top.T.AlertInfo.OperationFail, ack.hint, "error");
            }

            ifNd = document.getElementById("contentMainFrame");
            ifNd.src = ifNd.src + "?r=" + VALIDATION_STRING;
        });
    }

    /**
     *  download complete
     * @param {String} file, file path.
     */
    function dlComplete(file) {
        var cmd = 'download complete : path = "' + file + '";';
        LMT.cmdSyn(cmd, dlCompleteCallback);
    }

    function dlCompleteCallback(data) {
        if (-1 != data.indexOf("update_exception_sucess")) {
            setTimeout(Progress.updateReboot, 1000);
            return;
        }

        var ack = LMT.parser(data), //
            ifNd = document.getElementById("contentMainFrame");
        if (ack.result === "000") {
            Progress.updateReboot();
        } else {
            Modal.delProgress();
            Modal.open(top.T.AlertInfo.OperationFail, ack.hint, "error");
            ifNd.src = ifNd.src + "?r=" + VALIDATION_STRING;
        }
    }

    /**
     * 读取LMT脚本命令
     * @return {Object} ack object,which is parsed by LMT.parser()
     */
    function getLmtCommands() {
        var cmd = "get lmtCommands;", data = LMT.cmdAsyn(cmd);
        return LMT.parser(data);
    }

    /**
     * @return {Object} ack object,which is parsed by LMT.parser()
     */
    function getUserCommands() {
        var cmd = "get UserCommands;", data = LMT.cmdAsyn(cmd);
        return LMT.parser(data);
    }

    /**
     * download request请求,TD 用
     * @param {Function} callback
     */
    function downloadRequest(callback) {
        var cmd = "download request;";
        LMT.cmdSyn(cmd, callback);
    }

    /**
     * 退出登录
     * @param {Integer} msg, if undefined, prompt.
     */
    function logout(msg) {
        if (typeof (msg) === "undefined") {
            Modal.open(top.T.AlertInfo.LogoutConfirm, top.T.AlertInfo.LogoutMSG, "choice", logout);
            return;
        }
        if (window.parseInt(msg) === 1) {
            var roleValue = top.role;
            var usernameValue = top.username;
            $.post("/logout" + "?r=" + VALIDATION_STRING, {
                reqType: 14,
                rolePttr: roleValue,
                userNamePttr: usernameValue
            }, function (data) {
                window.top.location = 'home.asp';
            });
        }
    }

    /**
     * 导入数字证书
     * @param{String} path
     */
    function importCertrificate(path) {
        var cmd = "download certificate: path = \"" + path + "\"";
        Modal.progress(top.T.AlertInfo.Importing);
        LMT.cmdSyn(cmd, function (data) {
            var ack = LMT.parser(data), iframe = document.getElementById("contentMainFrame");
            Modal.delProgress();
            if (ack.result === "000") {
                Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.ImportSuccess, "ok");
            } else {
                Modal.open(top.T.AlertInfo.OperationFail, ack.hint, "error");
            }
            iframe.src = "business/config/BackupAndImportConfig.asp?r=" + top.VALIDATION_STRING + "&v=" + DeviceInfo.getPartialVersion();
        });
    }

    /**
     *  download dpcomplete
     * @param {String} file, file path.
     */
    function dpUpgrade(file) {
        var cmd = 'web Timeout: time=60;download dpcomplete : path = "' + file + '";';
        LMT.cmdSyn(cmd, dpUpgradeCallback);
    }

    function dpUpgradeCallback(data) {

        var ack = LMT.parser(data), //
            url = "business/config/dpUpgradeManager.asp", //
            ifNd = document.getElementById("contentMainFrame");

        if (ack.result === "000") {
            Modal.delProgress();
            //Progress.updateReboot();
            //Modal.open(top.T.AlertInfo.OperationSuccess, ack.hint, "error");
            Modal.open(top.T.AlertInfo.OperationSuccess, "DP Upgrade Success", "ok");
        } else {
            Modal.delProgress();
            Modal.open(top.T.AlertInfo.OperationFail, ack.hint, "error");
            ifNd.src = url + "?r=" + DeviceInfo.getPartialVersion();
        }
    }

    return {
        getSWpackageVersion: getSWpackageVersion,
        activePackage: activePackage,
        exportDatabase: exportDatabase,
        importDatabase: importDatabase,
        zipExportPackage: zipExportPackage,
        dlComplete: dlComplete,
        getLmtCommands: getLmtCommands,
        getUserCommands: getUserCommands,
        downloadRequest: downloadRequest,
        logout: logout,
        importCertrificate: importCertrificate,
        dpUpgrade: dpUpgrade
    };
}());

/**
 * 等待相关，重启、升级、恢复出厂、加载数据 ……
 */
var Progress = (function () {

    /**
     * 执行重启命令
     * @param {Integet} msg, if(msg === undefined) prompt, else if(msg ===1) reboot
     */
    function reBoot(msg) {
        if (typeof (msg) === "undefined") {
            Modal.open(top.T.AlertInfo.ResetSystemConfirm, top.T.AlertInfo.ResetSystemInfo, "choice", Progress.reBoot);
            return;
        }

        if (window.parseInt(msg) === 1) {
            Modal.progress(top.T.AlertInfo.Rebooting);

            var cmd = "reboot;";
            $("#contentMainFrame").attr("src", "");
            LMT.cmdSyn(cmd, function (data) {
                var ack = LMT.parser(data);
                if (ack.result !== "000") {
                    Modal.delProgress();
                    Modal.open(top.T.AlertInfo.OperationFail, ack.hint, "error");

                }
                $("#contentMainFrame").attr("src", "business/config/systemReset.html");
                Modal.delProgress();
                // setTimeout(gotofell, 1000 * 10);
            });
        }
    }

    //重激活
    function reActivate() {
        var cmd = "reActiveCell;";
        top.LMT.cmdSyn(cmd, function (data) {
            var ack = top.LMT.parser(data);
            if (ack.result === "000") {
                Priority = -1;
                top.Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.OperationSuccess, "ok");

            } else {
                top.Modal.open(top.T.AlertInfo.OperationFail, top.T.AlertInfo.TryAgainlater, "error");
            }
        });
    }

    /**
     * 正在重启，显示提示，cover ；进入检测重启完成进程
     */
    function reBooting() {
        Modal.progress(top.T.AlertInfo.Updating);
        setTimeout(gotofell, 1000 * 10);
    }

    /**
     * 循环检测设备是否重启完成
     */
        //定义新旧两个aspSleep.asp文件路径
    var newSleepURL = "/C/aspSleep.asp" + "?r=" + VALIDATION_STRING, oldSleepURL = "/business/config/aspSleep.asp", //
        sleepURL = newSleepURL;
    //是否重启过的标志位
    var isReboot = false;
    var sendTimes = 0;

    function gotofell() {
        $("#contentMainFrame").attr("src", "");
        var G_TimeOut = -1;
        setTimeout(function () {
            $.ajax({
                async: true,
                cache: false,
                type: 'post',
                timeout: 2000,
                url: sleepURL,
                data: {
                    "usecond": 1
                },
                success: function (data) {
                    sendTimes++;
                    clearTimeout(G_TimeOut);
                    if (isReboot) {
                        setTimeout(waittogotomain, 1000);
                    } else {
                        setTimeout(gotofell, 2000);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    //如果出错，在新旧的URL间切换尝试，兼容新版本回退重启到旧版本
                    sleepURL = (sleepURL === newSleepURL) ? newSleepURL : newSleepURL;
                    //网络不通，则正在重启

                    isReboot = true;
                    G_TimeOut = setTimeout(gotofell, 2000);
                }
            });
        }, 2000);
    }

    /**
     * 设备重启完成，提示刷到到主页还是登录页
     */
    function waittogotomain() {
        $.ajax({
            async: true,
            cache: false,
            type: 'post',
            timeout: 1000 * 11,
            url: "/C/function.asp" + "?r=" + top.VALIDATION_STRING,
            data: {
                "caseType": 6
            },
            success: function (data) {
                Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.GotoMainPageInfo, "choice", function (msg) {
                    if (window.parseInt(msg) === 1) {
                        window.top.location.reload();
                    } else {
                        System.logout(1);
                    }
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //如果出错，在新旧的密码，兼容新版本回退重启到旧版本

                Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.GotoHomePageInfo, "ok", function (msg) {
                    window.top.location = 'home.asp' + '?r=' + parseInt((100 * Math.random()), 10);
                });
            }
        });
    }

    /**
     * 刷新当前子页面，根据 URLManager.getURL() 获取URL
     */
    function reLoadChildPage() {
        var currentURL = URLManager.getURL();
        Modal.delProgress();
        $("#contentMainFrame").attr("src", currentURL + '?r=' + VALIDATION_STRING);
    }

    function updateReboot() {
        Modal.progress();
        var steps = [];
        steps.push(top.T.VersionManagementPage.FirewareUploadFinished);
        steps.push(top.T.VersionManagementPage.FirewareChecked);
        steps.push(top.T.VersionManagementPage.FirewareFinished);
        Modal.showSteps(steps);

        $.ajaxSetup({
            async: true,
            timeout: 1000
        });
        gotofell();
//      setTimeout(gotofell, 1000);
    }

    /* 文件上传成功探测 begin */
    var loadingfailTimes = 0, loadFinishFlag = false, interObj;

    /**
     * 上传文件submit后进入等到进程，loadType代表文件上传类型
     * 0:初始值，不使用 ;1: 升级；2：文件上传；
     * @param {Integer} loadType
     */
    function updateFeller(loadType) {
        loadFinishFlag = false;
        loadingfailTimes = 0;
        Modal.progress();
        interObj = setInterval(function () {
            updateFellerC(loadType);
        }, 2000);
    }

    function updateFellerC(loadType) {
        loadingfailTimes += 1;
        if (loadingfailTimes > 120) {
            clearInterval(interObj);
            Modal.open(top.T.AlertInfo.OperationFail, top.T.AlertInfo.FileUploadTimeout, "error");
        }

        $.ajax({
            type: 'post',
            async: true,
            url: '/C/fileload.asp' + "?r=" + VALIDATION_STRING,
            data: {
                caseType: 1
            },
            success: function (data) {
                clearInterval(interObj);
                if (1 === window.parseInt(data)) {
                    setTimeout(function () {
                        checkUploadFlag(loadType);
                    }, 5000);
                } else if (loadingfailTimes > 120) {
                    Modal.open(top.T.AlertInfo.OperationFail, top.T.AlertInfo.FileUploadTimeout, "error");
                }
            }
        });
    }

    function checkUploadFlag(loadType) {
        if (!loadFinishFlag) {
            $.ajax({
                type: 'post',
                async: true,
                url: '/C/fileload.asp' + "?r=" + VALIDATION_STRING,
                data: {
                    caseType: 2
                },
                success: function (data) {
                    data = data.split('|');
                    if (!data || data.length < 2) {
                        checkUploadFlag(loadType);
                    } else {
                        submit_upload(data[0], data[1], data[2], loadType);
                    }
                },
                error: function () {
                    checkUploadFlag(loadType);
                }
            });
        }
    }

    /**
     * 文件上传结束处理函数
     */
    function submit_upload(ret, typeName, pathName, loadType) {
        loadFinishFlag = true;
        clearInterval(interObj);
        if (typeof (loadType) === "undefined") {
            loadType = 0;
        } else {
            loadType = window.parseInt(loadType, 10);
        }

        if (1 === loadType) {
            Modal.showSteps([top.T.VersionManagementPage.FirewareUploadFinished, top.T.VersionManagementPage.FirewareChecking]);
        } else if (2 === loadType) {
            Modal.delProgress();
        }

        ret = window.parseInt(ret, 10);
        if (0 === ret) {
            if (-1 !== typeName.indexOf("webupdateUpload", 0)) {
                System.dlComplete(pathName);
            } else if ((-1 !== typeName.indexOf("webLmtUpload", 0)) || (-1 !== typeName.indexOf("uploadlmtlist.txt", 0))) {
                Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.ScriptUploadSuccess, "ok");
                reLoadChildPage();
            } else if (-1 !== typeName.indexOf("webImportInOutUpload", 0)) {
                System.importDatabase(pathName);
            } else if (-1 !== typeName.indexOf("webCacUpload", 0)) {
                System.importCertrificate(pathName);
            } else {
                var curAction = URLManager.getAction();
                if (curAction.indexOf("dpUpgrade:") == 0) {
                    Modal.showSteps([top.T.VersionManagementPage.FirewareUploadFinished, top.T.VersionManagementPage.FirewareChecking]);
                    System.dpUpgrade(curAction.split(":")[1]);
                } else {
                    Modal.open(top.T.AlertInfo.OperationSuccess, top.T.AlertInfo.SoftwareUploadSuccess, "ok");
                    reLoadChildPage();
                }
            }
        } else {
            switch (window.parseInt(ret)) {
                case -1:
                    Modal.open(top.T.AlertInfo.OperationFail, top.T.AlertInfo.InvalidFile, "error");
                    break;
                case -2:
                    Modal.open(top.T.AlertInfo.OperationFail, top.T.AlertInfo.TruncateFileFail, "error");
                    break;
                case -3:
                    Modal.open(top.T.AlertInfo.OperationFail, top.T.AlertInfo.TruncateFileFail, "error");
                    break;
                case -4:
                    Modal.open(top.T.AlertInfo.OperationFail, top.T.AlertInfo.FileRenameFail, "error");
                    break;
                case -5:
                    Modal.open(top.T.AlertInfo.OperationFail, top.T.AlertInfo.SpaceError, "error");
                    break;
                case -6:
                    Modal.open(top.T.AlertInfo.OperationFail, top.T.AlertInfo.FlashSpaceError, "error");
                    break;
                default:
                    break;
            }
            reLoadChildPage();
        }
    }

    return {
        submit_upload: submit_upload,
        updateFeller: updateFeller,
        updateReboot: updateReboot,
        reLoadChildPage: reLoadChildPage,
        reBooting: reBooting,
        reActivate: reActivate,
        reBoot: reBoot
    };
}());

/**
 * 告警相关
 */
var Alarm = (function () {

    /**
     * 执行 命令 “get CurrentAlarms;”
     * @return {Object} ack object,which is parsed by LMT.parser()
     */
    function getCurrentAlarms() {
        var cmd = "get CurrentAlarms;", data = LMT.cmdAsyn(cmd);
        return LMT.parser(data);
    }

    /**
     * 执行 命令 “get HistoryAlarms;”
     * @return {Object} ack object,which is parsed by LMT.parser()
     */
    function getHistoryAlarms() {
        var cmd = "get HistoryAlarms;", data = LMT.cmdAsyn(cmd);
        return LMT.parser(data);
    }

    /**
     * raise an alarm ……
     * @param {String} id
     * @param {String} State
     * @param {String} Cause
     * @return {Object} ack object,which is parsed by LMT.parser()
     */
    function raiseAlarm(id, state, cause) {
        var cmd = "raise alarm : id = \"" + id + "\", state = \"" + state + "\", cause = \"" + cause + "\";";
        var data = LMT.cmdAsyn(cmd);
        return LMT.parser(data);
    }

    return {
        getCurrentAlarms: getCurrentAlarms,
        getHistoryAlarms: getHistoryAlarms,
        raiseAlarm: raiseAlarm
    };
}());
